package com.xyz.frame.api.controller.xiangqin.auth.service.impl;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xyz.frame.api.controller.xiangqin.auth.request.SmsLoginRequest;
import com.xyz.frame.api.controller.xiangqin.auth.request.WxLoginRequest;
import com.xyz.frame.api.controller.xiangqin.auth.request.WechatPublicLoginRequest;
import com.xyz.frame.api.controller.xiangqin.auth.response.LoginResponse;
import com.xyz.frame.api.controller.xiangqin.auth.service.AppAuthService;
import com.xyz.frame.api.controller.xiangqin.sms.service.AppSmsService;
import com.xyz.frame.bean.model.User;
import com.xyz.frame.common.exception.XyzShopBindException;
import com.xyz.frame.security.common.bo.UserInfoInTokenBO;
import com.xyz.frame.security.common.enums.SysTypeEnum;
import com.xyz.frame.security.common.manager.TokenStore;
import com.xyz.frame.security.common.vo.TokenInfoVO;
import com.xyz.frame.service.UserXqService;
import lombok.extern.slf4j.Slf4j;
import org.shzhyun.pay.Service.WechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("appAuthService")
@Slf4j
public class AppAuthServiceImpl implements AppAuthService {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private UserXqService userService;

    @Autowired
    private AppSmsService appSmsService;
    
    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenStore tokenStore;

//    @Autowired
//    private JWTUtil jwtUtil;

//    public AppAuthServiceImpl(WxMaService wxMaService, UserXqService userService, AppSmsService appSmsService) {
//        this.wxMaService = wxMaService;
//        this.userService = userService;
//        this.appSmsService = appSmsService;
////        this.jwtUtil = jwtUtil;
//    }

    @Override
    public LoginResponse miniWxLogin(WxLoginRequest request) {
        LoginResponse response = new LoginResponse();
        String token = null;
        String sessionKey = null;
        String phone = null;
        try{
            sessionKey = wxMaService.getUserService().getSessionInfo(request.getCode()).getSessionKey();
            phone = wxMaService.getUserService().getPhoneNoInfo(sessionKey, request.getEncryptedData(), request.getIv()).getPhoneNumber();
            log.info("===>miniWxLogin=>phone:{}",phone);
        }catch (Exception e){
            e.printStackTrace();
            log.info("===>miniWxLogin=>e:{}=>getAppid:{}=>getSecret:{}",e.getMessage()
                    ,wxMaService.getWxMaConfig().getAppid()
                    ,wxMaService.getWxMaConfig().getSecret());
            throw new XyzShopBindException("微信小程序登录获取手机号获取失败");
        }

        LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(User::getMobile, phone);
        User user = userService.getOne(lambdaQueryWrapper);
        if(user == null){
            user = new User();
            user.setUid(UUID.fastUUID().toString());
            user.setMobile(phone);
            user.setCreateTime(new Date());
            user.setModifyTime(new Date());
            user.setUserRegtime(new Date());
            user.setGender(2);
            user.setPassword("123456");
            userService.save(user);
        }

//        token = jwtUtil.generateToken(User.getUid());
        log.info("===>miniWxLogin=>user:{}",user);


        UserInfoInTokenBO userInfoInToken = new UserInfoInTokenBO();
        userInfoInToken.setUserId(user.getUid());
        userInfoInToken.setSysType(SysTypeEnum.ORDINARY.value());
        userInfoInToken.setEnabled(true);
        // 存储token返回vo
        TokenInfoVO tokenInfoVO = tokenStore.storeAndGetVo(userInfoInToken);
        response.setToken(tokenInfoVO.getAccessToken());
        response.setUserId(tokenInfoVO.getUserId());
        log.info("===>miniWxLogin=>response:{}",response);
        return response;
    }

    @Override
    public LoginResponse smsLogin(SmsLoginRequest request) {

//        appSmsService.verifySmsCode(request.getMobileNo(), request.getCode());

        LoginResponse response = new LoginResponse();
        String token = null;

        LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(User::getMobile, request.getMobileNo());
        User user = userService.getOne(lambdaQueryWrapper);
        //手机号没有注册、直接注册
        if(user == null){
            user = new User();
            user.setUid(UUID.fastUUID().toString());
            user.setMobile(request.getMobileNo());
            user.setCreateTime(new Date());
            user.setModifyTime(new Date());
            user.setUserRegtime(new Date());
            user.setGender(2);
            user.setPassword(request.getCode());
            userService.save(user);
        }
        //手机号有注册、校验密码
        LambdaQueryWrapper<User> lambdaQueryWrapper2 = Wrappers.lambdaQuery();
        lambdaQueryWrapper2.eq(User::getMobile, request.getMobileNo());
        lambdaQueryWrapper2.eq(User::getPassword, request.getCode());
        User userExit = userService.getOne(lambdaQueryWrapper2);
        //手机号对应密码不对
        if(userExit == null){
            //密码错误
            return null;
        }

//        token = jwtUtil.generateToken(User.getUid());
//        response.setToken(token);

        UserInfoInTokenBO userInfoInToken = new UserInfoInTokenBO();
        userInfoInToken.setUserId(user.getUid());
        userInfoInToken.setSysType(SysTypeEnum.ORDINARY.value());
        userInfoInToken.setEnabled(true);
        // 存储token返回vo
        TokenInfoVO tokenInfoVO = tokenStore.storeAndGetVo(userInfoInToken);
        response.setToken(tokenInfoVO.getAccessToken());
        response.setUserId(tokenInfoVO.getUserId());
        return response;
    }

    @Override
    public LoginResponse wechatPublicLogin(WechatPublicLoginRequest request) {
        LoginResponse response = new LoginResponse();
        
        try {
            // 通过code获取用户信息
            com.alibaba.fastjson.JSONObject userInfo = wechatService.userinfo(request.getCode(), null);
            log.info("===>wechatPublicLogin=>userInfo:{}", userInfo);
            
            if (userInfo == null || userInfo.getString("openid") == null) {
                throw new XyzShopBindException("微信公众号登录获取用户信息失败");
            }
            
            String openid = userInfo.getString("openid");
            String unionid = userInfo.getString("unionid");
            
            // 查询用户是否已存在
            LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(User::getMpOpenId, openid); // 假设使用mpOpenId字段存储公众号openid
            User user = userService.getOne(lambdaQueryWrapper);
            
            // 如果用户不存在则创建新用户
            if (user == null) {
                user = new User();
                user.setUid(UUID.fastUUID().toString());
                user.setMpOpenId(openid);
                user.setUnionId(unionid);
                user.setCreateTime(new Date());
                user.setModifyTime(new Date());
                user.setUserRegtime(new Date());
                user.setGender("1".equals(userInfo.getString("sex")) ? 1 : 2); // 1为男性，2为女性
                user.setAvatar(userInfo.getString("headimgurl"));
                user.setUserName(userInfo.getString("nickname"));
                user.setPassword("123456"); // 默认密码
                userService.save(user);
            } else {
                // 更新用户信息
                user.setAvatar(userInfo.getString("headimgurl"));
                user.setUserName(userInfo.getString("nickname"));
                user.setModifyTime(new Date());
                userService.updateById(user);
            }

            log.info("===>wechatPublicLogin=>user:{}", user);

            UserInfoInTokenBO userInfoInToken = new UserInfoInTokenBO();
            userInfoInToken.setUserId(user.getUid());
            userInfoInToken.setSysType(SysTypeEnum.ORDINARY.value());
            userInfoInToken.setEnabled(true);
            // 存储token返回vo
            TokenInfoVO tokenInfoVO = tokenStore.storeAndGetVo(userInfoInToken);
            response.setToken(tokenInfoVO.getAccessToken());
            response.setUserId(tokenInfoVO.getUserId());
            log.info("===>wechatPublicLogin=>response:{}", response);
            return response;
            
        } catch (Exception e) {
            e.printStackTrace();
            log.error("===>wechatPublicLogin=>exception:{}", e.getMessage());
            throw new XyzShopBindException("微信公众号登录失败");
        }
    }
}